using JT808Protocol.Abstracts;
using JT808Protocol.Handlers;
using JT808Protocol.Models;
using System.Collections.Generic;
using System.Linq;

namespace JT808Protocol.Methods
{
    public class MsgHandlerContainer
    {
        //处理器队列
        private Queue<MsgHandlerBase> msgHandlerQueue;

        private List<MsgHandlerBase> _msgHandlers;

        private List<MsgHandlerBase> MsgHandlers
        {
            get
            {
                if (_msgHandlers == null)
                {
                    _msgHandlers = msgHandlerQueue.ToList();
                }
                return _msgHandlers;
            }
        }

        public MsgHandlerContainer(List<MsgHandlerBase> handlerCollection)
        {
            //初始化队列
            msgHandlerQueue = new Queue<MsgHandlerBase>();

            if (handlerCollection == null) handlerCollection = new List<MsgHandlerBase>();
            for (int i = 0; i < handlerCollection.Count; i++)
            {
                msgHandlerQueue.Enqueue(handlerCollection[i]);
            }
            //添加默认的平台通用应答处理器
            //特殊请求优先处理，最后才是平台通用响应处理
            msgHandlerQueue.Enqueue(new DefaultHandler());
        }

        /// <summary>
        /// 处理消息,并返回封装的相应消息
        /// </summary>
        /// <param name="package">设备包</param>
        /// <returns>平台响应包</returns>
        public JT808Package[] Handle(JT808Package package)
        {
            for (int i = 0; i < MsgHandlers.Count; i++)
            {
                //处理消息
                var results = MsgHandlers[i].Execute(package);
                if (results != null)
                    return results;
            }
            return null;
        }
    }
}